package com.frank.service.impl;

import com.frank.dao.StaffMapper;
import com.frank.dto.LoginDto;
import com.frank.model.Staff;
import com.frank.model.StaffCriteria;
import com.frank.service.StaffService;
import com.frank.service.TokenService;
import io.jsonwebtoken.JwtException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StaffServiceImpl implements StaffService {

    @Resource
    private TokenService tokenService;

    @Resource
    private StaffMapper staffMapper;

    @Override
    public LoginDto loginService(String phoneNum, String password) {

        StaffCriteria staffCriteria = new StaffCriteria();
        staffCriteria.createCriteria().andPhoneEqualTo(phoneNum).andPasswordEqualTo(password);
        List<Staff> staffs = staffMapper.selectByExample(staffCriteria);
        if (staffs.isEmpty()){
            return null;
        }
        return new LoginDto(tokenService.createToken(phoneNum,password), phoneNum, staffs.get(0).getStaffName(), staffs.get(0).getId());
    }

    @Override
    public boolean registerService(String phoneNum, String password) {
        Staff staff = new Staff();
        staff.setPhone(phoneNum);
        staff.setPassword(password);
        return staffMapper.insertSelective(staff) == 1;
    }

    @Override
    public boolean checkToken(String token) {
        StaffCriteria staffCriteria = new StaffCriteria();

        try {
            String phone = tokenService.parseToken(token);
            staffCriteria.createCriteria().andPhoneEqualTo(phone);
        }catch (JwtException e){
            return false;
        }

        List<Staff> staffList = staffMapper.selectByExample(staffCriteria);

        return !staffList.isEmpty();
    }
}
